package com.novel.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.novel.common.enums.BeAuthorStatusEnum;
import com.novel.common.enums.UserIdentifyEnum;
import com.novel.common.exception.CustomerException;
import com.novel.common.vo.ApplyAuthorVo;
import com.novel.mapper.ApplyAuthorMapper;
import com.novel.mapper.UserMapper;
import com.novel.pojo.system.ApplyAuthor;
import com.novel.pojo.system.User;
import com.novel.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApplyAuthorService {

    @Autowired
    private ApplyAuthorMapper applyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailUtils mailUtils;


    /**
     * 分页查询申请记录
     */
    public PageInfo<ApplyAuthorVo> queryApplyAuthorInfoByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        Example example = new Example(ApplyAuthor.class);
        example.setOrderByClause("created_time desc");
        example.createCriteria().andEqualTo("status", BeAuthorStatusEnum.WAIT.getCode());
        List<ApplyAuthor> applyAuthorList = applyMapper.selectByExample(example);

        return new PageInfo<>(applyAuthorList.stream().map(ApplyAuthorVo::convert).collect(Collectors.toList()));
    }

    /**
     * 查询申请记录
     */
    public ApplyAuthor findApplyAuthorInfo(String userId) {
        Example example = new Example(ApplyAuthor.class);
        example.createCriteria()
                .andEqualTo("userId", userId)
                .andEqualTo("status", BeAuthorStatusEnum.WAIT.getCode());
        List<ApplyAuthor> applyAuthorList = applyMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(applyAuthorList)) {
            return null;
        }
        return applyAuthorList.get(applyAuthorList.size() - 1);
    }

    /**
     * 添加申请记录
     * 申请成为作家
     */
    @Transactional
    public boolean insertApplyAuthorInfo(ApplyAuthor applyAuthor) {
        return applyMapper.insert(applyAuthor) == 1;
    }

    /**
     * 取消申请
     */
    public boolean cancelApplyAuthor(String userId, String id, String ip) {
        ApplyAuthor record = applyMapper.selectByPrimaryKey(id);
        if (record == null || !StringUtils.equals(userId, record.getUserId()) ||
                record.getStatus() != BeAuthorStatusEnum.WAIT.getCode()) {
            throw new CustomerException("没有对应的申请记录可以取消");
        }
        record.setStatus(BeAuthorStatusEnum.CANCEL.getCode());
        record.setUpdatedTime(new Date());
        record.setUpdatedId(userId);
        record.setUpdatedIp(ip);
        return applyMapper.updateByPrimaryKey(record) == 1;
    }

    /**
     * 通过申请
     * 1.修改申请状态
     * 2.修改用户权限
     * 3.发邮件提醒用户
     */
    @Transactional
    public boolean passApplyAuthor(String id, String userId, String ip) {
        ApplyAuthor record = applyMapper.selectByPrimaryKey(id);

        if (record.getStatus() != BeAuthorStatusEnum.WAIT.getCode()) {
            throw new CustomerException("该申请无法处理!");
        }
        record.setStatus(BeAuthorStatusEnum.PASS.getCode());
        record.setUpdatedTime(new Date());
        record.setUpdatedId(userId);
        record.setUpdatedIp(ip);

        if (applyMapper.updateByPrimaryKeySelective(record) == 1) {
            boolean result = userMapper.updateUserPermission(record.getUserId(), UserIdentifyEnum.AUTHOR.getCode()) == 1;

            if (result) {
                mailUtils.sendEmail(record.getUserEmail(),
                        "恭喜你,亲爱的用户,你通过了作者申请",
                        "恭喜你通过作者申请,从现在开始你就是本网站的一名作者了!");
            }

            return result;
        }
        throw new CustomerException("申请处理失败!");
    }

    /**
     * 拒绝申请
     */
    @Transactional
    public boolean rejectUserApplyAuthor(String id, String userId, String ip) {
        ApplyAuthor record = applyMapper.selectByPrimaryKey(id);

        if (record.getStatus() != BeAuthorStatusEnum.WAIT.getCode()) {
            throw new CustomerException("该申请无法处理!");
        }
        record.setStatus(BeAuthorStatusEnum.REJECT.getCode());
        record.setUpdatedTime(new Date());
        record.setUpdatedId(userId);
        record.setUpdatedIp(ip);

        boolean result = applyMapper.updateByPrimaryKey(record) == 1;

        if (result) {
            mailUtils.sendEmail(record.getUserEmail(),
                    "对不起,亲爱的用户,你没有通过申请",
                    "对不起,亲爱的用户,你没有通过申请");
        }
        return result;
    }


}